#!/usr/bin/php -q
<?php
   set_time_limit(30);
   require('phpagimihira.php');
   require('sqlmihira.php');
   error_reporting(E_ALL);
     
   $agi = new AGI();
   $agi->answer();

   
   $cid = $agi->parse_callerid();
   $agi->verbose('Extension................');
   $agi->verbose($agi->request['agi_extension']);
   $direction=$argv[1];
   $db = new AGIDB($agi);
   
   
   
   //============================Configurations=======================================================
   $db->dbname = 'classified';
   $db->dbuser = 'root';
   $db->dbpass = 'abc123'; 
   $landsparentid=2;
   $vehiclesparentid=1;
   $subscriptionvalidity=30;
   $suggestingradius=10;
   $smsserver="10.2.28.9";
   $smsport=13005;
   $smsusername="dcuser";
   $smspassword="dcuser123";
   //============================Configurations=======================================================
   
 
   $msisdn=$direction=='out'?$argv[2]:str_replace("+", "", $cid['username']);
   
   
   
   function increase_clasification_rank($parents){
   		global $db;
   		$itemstring=$parents[0]['itemid'];
   		for ($i = 1; $i < sizeof($parents); $i++) {
   			
   			$itemstring=$itemstring.",".$parents[$i]['itemid'];
   			
   		}
   		
   		$res = $db->sql("update `classification` set `rank`=`rank`+1 where `itemid` in (".$itemstring.")","NONE");	
   	
   }
   
   function getparents($itemid){
	//array_push($promptlist,array('prompt'=>'activeadverts', 'name'=>'activeadverts
   	global $db;   	
   	$parents=array();
   	while(true){
   		$res = $db->sql("SELECT `itemid`,`parentid`,`name`,concat('classification/',`prompt`) as `prompt` from `classification` where `itemid`='".$itemid."'", "ASSOC");    // get prompt parent
   		array_unshift($parents,$res[0]);
   		$itemid=$res[0]['parentid'];
   			
   		if ($res[0]['parentid']<=10){
   			break;
   		}
   	}
   	
   	return $parents;
   	
   	
   }
  
   function get_classified_prompt($itemid)
   {
		global $db;
        $res = $db->sql("SELECT concat('classification/',`prompt`) as `prompt` from `classification` where `itemid`=".$itemid, "ASSOC");    // get prompt name
        return $res[0]['prompt'];

   }

   function charge_customer($msisdn, $chargevent, $description){
   	
   		return 1;			// to be removed when charging implemented
	   	$ch = curl_init();
	   	curl_setopt($ch, CURLOPT_URL, "http://10.1.80.21:8080/cgi-bin/erl/omniecg_web/chrg_sub?ContentProvider=APALYA&MSISDN=".$msisdn."&SERVICECODE=".$chargevent."&Description=Optional");
	   	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	   	$output = curl_exec($ch);
	   	curl_close($ch);
	   	
	   	if ($output==1 || $output==0)
	   	{
	   		return $output;
	   	}
	   	else
	   	{
	   		return -1;   	
	   	}
	   	  	
   }
   
   function send_sms($destination, $origination, $msg){  
   		global $smsserver,$smsport,$smsusername,$smspassword,$agi;
   		//return ; 	
	   	$ch = curl_init();
	   	//curl_setopt($ch, CURLOPT_URL, "http://localhost:8970/cgi-bin/sendsms?username=jjjjj&password=lllll&from=".$origination."&to=".$destination."&text=".$msg);
	   	curl_setopt($ch, CURLOPT_URL, "http://".$smsserver.":".$smsport."/cgi-bin/sendsms?username=".$smsusername."&password=".$smspassword."&from=".$origination."&to=".$destination."&text=".urlencode($msg));
	   	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	   	$output = curl_exec($ch);
	   	curl_close($ch);
	   	$agi->verbose("Curl utput".$output);
	   	 
	   	return $output;
   }
   
   function subscribe_customer($msisdn,$servicetype,$serviceid,$parents)
   {
		global $agi,$db,$promptroot,$subscriptionvalidity;
		
	 	$res = $db->sql("SELECT `msisdn`, `servicetype`,`serviceitem`,`status` from `subscriptions` where `serviceitem`=".$serviceid." and `msisdn`='".$msisdn."'", "ASSOC"); // chk for any previous subscriptions
	 	$agi->verbose(var_export($res,true));
	 	if (sizeof($res)==0){
	 		
	 		 $chargeres=charge_customer($msisdn, "SUBSCRIPTION", $servicetype);	// Charge the customer
	 		 generate_cdr($msisdn, $servicetype, "SUBSCRIPTION-REG", $chargeres);
	 		 if($chargeres==1){
	 		 	$res=null;
	 		 	$res = $db->sql("insert into subscriptions SELECT null as `subscriptionid`, CURRENT_TIMESTAMP as `activatedtime`,'".$msisdn."' as `msisdn`, '".$servicetype."' as `servicetype`,".$serviceid." as `serviceitem` ,'ACTIVE' as `status`, null as `lastalertsenttime`, '".date('Y-m-d', strtotime("+".$subscriptionvalidity." days"))."' as `expiredate`, max(id)as `startalertid`,max(id)as `lastalertid`, 0 as `alertcount` FROM `alertstatus` where `delivered`=1 ", "NONE");    // insert the subscription
	 		 	
	 		 	if ($servicetype=='vehicles')
	 		 		send_sms($msisdn, '289', "you've subscribed for SMS alerts on ".(sizeof($parents)==3?$parents[2]['name'].",":"").(sizeof($parents)>1?$parents[1]['name']:$parents[0]['name']).".(Rs.50+tax, Valid for 30 days). Will be auto renewed upon expiry. Dial 289 to unsubscribe.");
	 		 	else 
	 		 		send_sms($msisdn, '289', "you've subscribed for SMS alerts on lands in ".(sizeof($parents)==3?$parents[2]['name'].",":"").(sizeof($parents)>1?$parents[1]['name']:$parents[0]['name']).".(Rs.50+tax, Valid for 30 days). Will be auto renewed upon expiry. Dial 289 to unsubscribe.");
	 		 	
	 		 	increase_clasification_rank($parents);
 		 		$agi->stream_file($promptroot.'subscriptionactivated', '');               // play the sucessfully completed prompt
 		 		
 		 		$selection=-1;
 		 		$selection=$agi->play_menu($promptroot.$servicetype.'postsubscriptionmenu','123',3);
 		 		return $selection;
	 		 	
	 		 	
	 		 }
	 		 else if($chargeres==0){	// insufficient balance
	 		 	$agi->stream_file($promptroot.'failedinsuff', '');
	 		 	$agi->hangup();
	 		 }
	 		 else {		// TEmp Error
	 		 	$agi->stream_file($promptroot.'temperror', '');
	 		 	$agi->hangup();
	 		 }
	 		
	 		
	 	}
	 	else{
	 		$agi->stream_file($promptroot.'subscribedalready', '');		// Already Activated
	 		$selection=-1;
	 		$selection=$agi->play_menu($promptroot.$servicetype.'postsubscriptionmenu','123',3);
	 		return $selection;
	 	}
	 	
   }

   function generate_cdr($msisdn,$servicetype,$activity,$status)
   {
   	global $agi,$db;
   	$res = $db->sql("INSERT INTO `cdr`(`id`, `entrytime`, `servicetype`, `msisdn`, `activity`, `status`) VALUES (null,null,'".$servicetype."','".$msisdn."','".$activity."','".$status."')", "NONE"); // chk for any previous subscriptions
   	   	
   }
    
   
   function deleteadvert($msisdn,$servicetype,$advertid,$filename)
   {
        global $agi,$db,$promptroot;
        $res = $db->sql("delete from `adverts` where `advertid`=".$advertid);    // delete the subscription
        $res = $db->sql("delete from `alerts`  where `advertid`='".$advertid."'");        
        $output = shell_exec("rm -f ".$filename.".gsm");
		generate_cdr($msisdn,$servicetype,"DELETE-ADVERT-".$advertid,'1');
        $agi->stream_file($promptroot.'advertdeleted', '');               // play the sucessfully deleted the advert
        send_sms($msisdn, '289', "you've successfully deleted the advertisment No.".$advertid);

   }

   function deactivate_advert($msisdn,$servicetype,$advertid)
   {
        global $agi,$db,$promptroot;       
		$res = $db->sql("update `adverts` set `status`='INACTIVE' where `advertid`='".$advertid."'");    // delete the subscription
		$res = $db->sql("update `alerts` set `status`='INACTIVE' where `advertid`='".$advertid."'");
        generate_cdr($msisdn,$servicetype,"DEACTIVATE-ADVERT-".$advertid,'1');
        $agi->stream_file($promptroot.'advertdeactivated','');             // play the sucessfully deleted the advert
        send_sms($msisdn, '289', "you've successfully deactivated the advertisment No.".$advertid);
        
   }

   function activateadvert($msisdn,$servicetype,$advertid)
   {
        global $agi,$db,$promptroot,$subscriptionvalidity;
        
        $chargeres=charge_customer($msisdn, "ACTIVATEADVERT", $servicetype);	// Charge the customer
        if($chargeres==1){
        	$res=null;
        	$db->sql("update `adverts` set `status`='ACTIVE' where `advertid`='".$advertid."'");    // delete the subscription
        	$alertsarray = $db->sql("select `alertid` from `alerts` where `advertid`='".$advertid."'","YES");
        	$i=0;
        	foreach ($alertsarray as $alert) {
        		$alertsarray[$i]=$alert['alertid'];        		
        		$i++;
        	}        	
        	$alerts="'".implode("','", array_values($alertsarray))."'";
	        $db->sql("insert into `alerts` SELECT null, `activatedtime`, `msisdn`, `serviceitem`, `servicetype`, `advertid`, `param1`, `param2`, `param3`, `param4`, `param5`, `param6`, `param7`, `param8`, `param9`, `param10`, `param11`, `operator`, 'ACTIVE' as `status`,  '".date('Y-m-d', strtotime("+".$subscriptionvalidity." days"))."' as `expiredate`, `smseng`, `smssin`, `smstam` FROM `alerts` WHERE `advertid`='".$advertid."'");
	        $db->sql("delete from `alerts` WHERE `alertid` in (".$alerts.")");
	        generate_cdr($msisdn,$servicetype,"ACTIVATE-ADVERT-".$advertid,$chargeres);
	        $agi->stream_file($promptroot.'advertactivated', '');               // play the sucessfully deleted the advert
	        send_sms($msisdn, '289', "you've successfully activated the advertisment No.".$advertid);
        }
        else if($chargeres==0){	// insufficient balance
        	generate_cdr($msisdn,$servicetype,"ACTIVATE-ADVERT-".$advertid,$chargeres);
        	$agi->stream_file($promptroot.'failedinsuff', '');
        	$agi->hangup();
        }
        else {		// TEmp Error
        	generate_cdr($msisdn,$servicetype,"ACTIVATE-ADVERT-".$advertid,$chargeres);
        	$agi->stream_file($promptroot.'temperror', '');
        	$agi->hangup();
        }
        
        
        
        

   }

   function publish_advert($msisdn,$language,$servicetype,$filename)
   {
   	global $agi,$db,$promptroot;
   	
   	$chargeres=charge_customer($msisdn, "PUBLISHADVERT", $servicetype);	// Charge the customer
   	if($chargeres==1){
   		$res=null;
   		$db->sql("INSERT INTO `adverts`(`language`, `servicetype`, `msisdn`, `promptname`,`status`) VALUES ('".$language."','".$servicetype."','".$msisdn."','".$filename."','UNPROCESSED')","NONE");    // insert the advert entry
   		$agi->stream_file($promptroot.'advertcompleted', '');
   		$res=$db->sql("SELECT `advertid` FROM `adverts` WHERE `msisdn`='".$msisdn."' and `promptname`='".$filename."'","YES");    // insert the advert entry
   		generate_cdr($msisdn,$servicetype,"PUBLISH-ADVERT-".$res[0]['advertid'],$chargeres);
   		send_sms($msisdn, '289', "you've successfully published your advertisment. Please note the reference ID:".$res[0]['advertid']);
   		
   	}
   	else if($chargeres==0){	// insufficient balance
   		generate_cdr($msisdn,$servicetype,"PUBLISH-ADVERT",$chargeres);
   		$agi->stream_file($promptroot.'failedinsuff', '');
   		$agi->hangup();
   	}
   	else {		// TEmp Error
   		generate_cdr($msisdn,$servicetype,"PUBLISH-ADVERT",$chargeres);
   		$agi->stream_file($promptroot.'temperror', '');
   		$agi->hangup();
   	}
   	
   }
   
   function deletesubscription($msisdn,$servicetype,$parents,$subscriptionid)
   {
        global $agi,$db,$promptroot;
        $res = $db->sql("delete from subscriptions where `subscriptionid`=".$subscriptionid);    // delete the subscription
        generate_cdr($msisdn, $servicetype, "SUBSCRIPTION-DELETE", '1');
        if ($servicetype=='vehicles')
        	send_sms($msisdn, '289', "You have successfully removed the SMS alert service on ".(sizeof($parents)==3?$parents[2]['name'].",":"").(sizeof($parents)>1?$parents[1]['name']:$parents[0]['name'])." Thank you for using DeepCee Easy Add.");
        else
        	send_sms($msisdn, '289', "You have successfully removed the SMS alert service on lands in ".(sizeof($parents)==3?$parents[2]['name'].",":"").(sizeof($parents)>1?$parents[1]['name']:$parents[0]['name'])." Thank you for using DeepCee Easy Add.");
        
        $agi->stream_file($promptroot.'subscriptiondeleted','');             // play the sucessfully deleted the Subscription

   }

   function deactivatesubscription($msisdn,$servicetype,$parents,$subscriptionid)
   {
        global $agi,$db,$promptroot;
		$res = $db->sql("update subscriptions set `status`='INACTIVE' where `subscriptionid`=".$subscriptionid);    //  ctivatedsubscription
		generate_cdr($msisdn, $servicetype, "SUBSCRIPTION-DEACTIVATE", '1');
		if ($servicetype=='vehicles')
			send_sms($msisdn, '289', "You have successfully unsubscribed from receiving for SMS alerts on ".(sizeof($parents)==3?$parents[2]['name'].",":"").(sizeof($parents)>1?$parents[1]['name']:$parents[0]['name'])." Thank you for using DeepCee Easy Add.");
		else
			send_sms($msisdn, '289', "You have successfully unsubscribed from receiving for SMS alerts on lands in ".(sizeof($parents)==3?$parents[2]['name'].",":"").(sizeof($parents)>1?$parents[1]['name']:$parents[0]['name'])." Thank you for using DeepCee Easy Add.");
		
		
		$agi->stream_file($promptroot.'subscriptiondeactivated','');             // play the sucessfully deactivated the Subscription

   }

   function activatesubscription($msisdn,$servicetype,$parents,$subscriptionid)
   {
        global $agi,$db,$promptroot;
         
        $chargeres=charge_customer($msisdn, "SUBSCRIPTION-ACTIVATE", $servicetype);	// Charge the customer
        generate_cdr($msisdn, $servicetype, "SUBSCRIPTION-ACTIVATE", $chargeres);
        if($chargeres==1){
        	$res=null;
        	$res = $db->sql("update subscriptions set `status`='ACTIVE' where `subscriptionid`=".$subscriptionid);    // delete the subscription
        
        	if ($servicetype=='vehicles')
        		send_sms($msisdn, '289', "Your subscription for SMS alerts on ".(sizeof($parents)==3?$parents[2]['name'].",":"").(sizeof($parents)>1?$parents[1]['name']:$parents[0]['name'])." was renewed for 30 days(Rs.50+tax). Will be auto renewed upon expiry. Dial 289 to unsubscribe.");
        	else
        		send_sms($msisdn, '289', "Your subscription for SMS alerts on lands in ".(sizeof($parents)==3?$parents[2]['name'].",":"").(sizeof($parents)>1?$parents[1]['name']:$parents[0]['name'])." was renewed for 30 days(Rs.50+tax). Will be auto renewed upon expiry. Dial 289 to unsubscribe.");
        
        	increase_clasification_rank($parents);
        	$agi->stream_file($promptroot.'subscriptionactivated','');                // play the sucessfully completed prompt
        
        	
        
        }
        else if($chargeres==0){	// insufficient balance
        	$agi->stream_file($promptroot.'failedinsuff', '');
        	$agi->hangup();
        }
        else {		// TEmp Error
        	$agi->stream_file($promptroot.'temperror', '');
        	$agi->hangup();
        }
         
        
        
        
        
        
        
        $res = $db->sql("update subscriptions set `status`='ACTIVE' where `subscriptionid`=".$subscriptionid);    // delete the subscription
        
        $agi->stream_file($promptroot.'subscriptionactivated','');             // play the sucessfully activated the Subscription
	
   }

   function manage_registrations($registrationtype,$servicetype="'lands','vehicles'")
   {

	    ManageRegistrations:
		global $agi,$db,$msisdn,$language,$promptroot;
		$agi->verbose(var_export($registrationtype,true));
	
		$counter=0;
	    $promptlist=null;	
		if($registrationtype['unprocessedadverts'])
		{
			$unprocessedadverts = $db->sql("SELECT `advertid`,`servicetype`,concat('/var/lib/asterisk/sounds/classifiedadverts/',`promptname`) as `promptname` FROM `adverts` WHERE `msisdn`='".$msisdn."' and `status`='UNPROCESSED' and `servicetype` in (".$servicetype.") order by `entrytime`", "ASSOC");
			$agi->verbose(var_export($unprocessedadverts,true));
			if (sizeof($unprocessedadverts)>0)
	                {
	                	$promptlist=array(array('prompt'=>'unprocessedadverts', 'name'=>'unprocessedadverts','list'=>$unprocessedadverts));
	                        $counter++;
	                }
		}
		if($registrationtype['activeadverts'])
	    {
		        $activeadverts = $db->sql("SELECT `advertid`,`servicetype`,concat('/var/lib/asterisk/sounds/classifiedadverts/',`promptname`) as `promptname` FROM `adverts` WHERE `msisdn`='".$msisdn."' and `status`='active' and `servicetype` in (".$servicetype.")  order by `entrytime`", "ASSOC");
                if (sizeof($activeadverts)>0)
                {
	                if (is_null($promptlist))
        	                $promptlist=array(array('prompt'=>'activeadverts', 'name'=>'activeadverts','list'=>$activeadverts));
                        else
                                array_push($promptlist,array('prompt'=>'activeadverts', 'name'=>'activeadverts','list'=>$activeadverts));

                        $counter++;
                }
		}
		if($registrationtype['inactiveadverts'])
        {
	        $inactiveadverts = $db->sql("SELECT `advertid`,`servicetype`,concat('/var/lib/asterisk/sounds/classifiedadverts/',`promptname`) as `promptname` FROM `adverts` WHERE `msisdn`='".$msisdn."' and `status` in ('INACTIVE','deactivated') and `servicetype` in (".$servicetype.") order by `entrytime`", "ASSOC");
        	if (sizeof($inactiveadverts)>0)
	        {
        	        if (is_null($promptlist))
                	        $promptlist=array(array('prompt'=>'inactiveadverts', 'name'=>'inactiveadverts','list'=>$inactiveadverts));
	                else
        	                array_push($promptlist,array('prompt'=>'inactiveadverts', 'name'=>'inactiveadverts','list'=>$inactiveadverts));

                	$counter++;
        	}
		}
        if($registrationtype['activesubscriptions'])
        {
                $activesubscriptions = $db->sql("SELECT `subscriptionid`,`servicetype`,`serviceitem` FROM `subscriptions`  WHERE `msisdn`='".$msisdn."' and `status` ='active' and `servicetype` in (".$servicetype.") order by `activatedtime`", "ASSOC");
                if (sizeof($activesubscriptions)>0)
                {
                        if (is_null($promptlist))
                                $promptlist=array(array('prompt'=>'activesubscriptions', 'name'=>'activesubscriptions','list'=>$activesubscriptions));
                        else
                                array_push($promptlist,array('prompt'=>'activesubscriptions', 'name'=>'activesubscriptions','list'=>$activesubscriptions));

                        $counter++;
                }
        }
        if($registrationtype['inactivesubscriptions'])
        {
                $inactivesubscriptions = $db->sql("SELECT `subscriptionid`,`servicetype`,`serviceitem` FROM `subscriptions`  WHERE `msisdn`='".$msisdn."' and `status` in ('inactive','deactivated') and servicetype in (".$servicetype.") order by activatedtime", "ASSOC");
                if (sizeof($inactivesubscriptions)>0)
                {
                        if (is_null($promptlist))
                                $promptlist=array(array('prompt'=>'inactivesubscriptions', 'name'=>'inactivesubscriptions','list'=>$inactivesubscriptions));
                        else
                                array_push($promptlist,array('prompt'=>'inactivesubscriptions', 'name'=>'inactivesubscriptions','list'=>$inactivesubscriptions));

                        $counter++;
                }
        }
        if ($counter==0)
        {
                 return 97;	//no registrations
        }
        else
        {
	        
				$agi->verbose(var_export($promptlist,true));
				$selection=-1;
				$selection=$agi->play_dynamic_menu($promptroot,$promptlist); 
				if($selection==99)      // go back
	        	{
	                	return 99;
		        }
	        	elseif($selection==98)          // go to main
		        {
	        	        return 98;
		        }
	        	else            // item selected
		        {
		
					if ($promptlist[$selection]['name']=='unprocessedadverts')
					{
						$advertlist=$promptlist[$selection]['list'];
						$count=0;
						while ($count<sizeof($advertlist))
						{
							$playlist=array($promptroot.'advertno',$promptroot.'digits/'.($count+1), $advertlist[$count]['promptname']);
							$agi->stream_concatenated_prompts($playlist,'');
							if($count==sizeof($advertlist)-1)
							{
								$selection=-1;
								$selection=$agi->play_menu($promptroot.'manageunprocessedadvertsmenu2','123');
							}
							else
							{
								
								$selection=-1;
								$selection=$agi->play_menu($promptroot.'manageunprocessedadvertsmenu1','1234');
							}
		
							if($selection=='1')      // delete this advert
					        {
	        	                	deleteadvert($msisdn,$advertlist[$count]['servicetype'],$advertlist[$count]['advertid'],$advertlist[$count]['promptname']);
	        	                	unset($advertlist[$count]);
	        	                	$advertlist=array_values($advertlist);
									
					        }
					        else if($selection=='2')      // record again
					        {
					        	RecordStart2:
					   			$agi->stream_file($promptroot.'recordstart', '');
					   			$filename=date("YmdHis")."-".$msisdn;
					   			$agi->record_file("classifiedadverts/".$filename, 'gsm','#', 20000, NULL, true, NULL);
					   				
					   			PostRecord2:
					   			$selection=-1;
					   			$selection=$agi->play_menu($promptroot.'postrecordmenu','123',3);
					   
					   			if($selection=='3')
					   			{
					   				$output = shell_exec("rm -f /var/lib/asterisk/sounds/classifiedadverts/".$filename.".gsm");
					   				goto RecordStart2;
					   			}
					   			elseif($selection=='1')
					   			{
					   				$output = shell_exec("rm -f ".$advertlist[$count]['promptname'].".gsm");					   				
					   				$res = $db->sql("update `adverts` set `promptname`='".$filename."'","NONE");    // insert the advert entry
					   				$agi->stream_file($promptroot.'advertcompleted', '');
					   				goto ManageRegistrations;
					   			}
					   			elseif($selection=='2')
					   			{
					   				$agi->stream_file('/var/lib/asterisk/sounds/classifiedadverts/'.$filename, '');
					   				goto PostRecord2;
					   			}
					   			else
   									$agi->hangup();
					        }
				        	elseif($selection=='3'&& $count==0)          // go to previous menu
					        {
					                goto ManageRegistrations;
					        }
					        elseif($selection=='3')          // go back to the previous item
				        	{
								$count--;
							}
	        	            elseif($selection=='3')          // go to the next item
	                	    {
	                        	$count++;
	                        }
		
						}
						return 98;
					
					}
					elseif($promptlist[$selection]['name']=='activeadverts')
					{
						$advertlist=$promptlist[$selection]['list'];
                	    $count=0;
                        while ($count<sizeof($advertlist))
	                    {
        	            	$playlist=array($promptroot.'advertno',$promptroot.'digits/'.($count+1), $advertlist[$count]['promptname']);
                	        $agi->stream_concatenated_prompts($playlist,'');
                        	if($count==sizeof($advertlist)-1)
                        	{
                        		$selection=-1;
                        		$selection=$agi->play_menu($promptroot.'manageactiveadvertsmenu2','12');
                        	}
	                        else{
	                        	$selection=-1;
	                        	$selection=$agi->play_menu($promptroot.'manageactiveadvertsmenu1','123');
	                        }

                	        if($selection=='1')      // delete this advert
                        	{
                            	deactivate_advert($msisdn,$advertlist[$count]['servicetype'],$advertlist[$count]['advertid']);                                       
								return 98;
	                        }
        	                elseif($selection=='2'&& $count==0)          // go to previous menu
                	        {
                        	     goto ManageRegistrations;
                	        }
	                        elseif($selection=='2')          // go back to the previous item
        	                {
                	             $count--;
                        	}
                            elseif($selection=='3')          // go to the next item
	                        {
        	                     $count++;
                	        }
						}
	
					}
					elseif($promptlist[$selection]['name']=='inactiveadverts')
					{
							$advertlist=$promptlist[$selection]['list'];
	                        $count=0;
        	                while ($count<sizeof($advertlist))
                	        {
                        	        $playlist=array($promptroot.'advertno',$promptroot.'digits/'.($count+1), $advertlist[$count]['promptname']);
                                	$agi->stream_concatenated_prompts($playlist,'');
	                                if($count==sizeof($advertlist)-1)
	                                {
	                                	$selection=-1;
	                                	$selection=$agi->play_menu($promptroot.'manageinactiveadvertsmenu2','123');
	                                }
                	                else
                	                {
                	                	$selection=-1;
                	                	$selection=$agi->play_menu($promptroot.'manageinactiveadvertsmenu1','1234');
                	                }
	
        	                        if($selection=='1')      // Activate this advert
                	                {
                        	                activateadvert($msisdn,$advertlist[$count]['servicetype'],$advertlist[$count]['advertid']);
											return 98;
	                                }
									elseif($selection=='2')      // delete this advert
                                    {
                                    	deleteadvert($msisdn,$advertlist[$count]['servicetype'],$advertlist[$count]['advertid'],$advertlist[$count]['promptname']);
                                        return 98;
                                    }
        	                        elseif($selection=='3'&& $count==0)          // go to previous menu
                	                {
                        	                goto ManageRegistrations;
                                	}
	                                elseif($selection=='3')          // go back to the previous item
        	                        {
                	                        $count--;
                        	        }
                                	elseif($selection=='4')          // go to the next item
	                                {
        	                                $count++;
									}
							}
					}			
                        
					elseif($promptlist[$selection]['name']=='activesubscriptions')
					{
						$subscriptionlist=$promptlist[$selection]['list'];
						$count=0;
						while ($count<sizeof($subscriptionlist))
						{
							$parents=getparents($subscriptionlist[$count]['serviceitem']);
							$agi->verbose($subscriptionlist[$count]['serviceitem'] ,true);
							if ($subscriptionlist[$count]['servicetype']=='lands' && $language=='eng')
							{
								$playlist=array($promptroot.'subscriptionno',$promptroot.'digits/'.($count+1), $promptroot.'playsubscription-lands-part1',$promptroot.'playsubscription-lands-part2',sizeof($parents) >2?$promptroot.'playsubscription-lands-part3':"",sizeof($parents) >2?$promptroot.$parents[2]['prompt']:"",sizeof($parents) >2?$promptroot.'playsubscription-lands-part4':"",$promptroot.'playsubscription-lands-part5',$promptroot.$parents[1]['prompt']);
								
							}
							elseif ($subscriptionlist[$count]['servicetype']=='lands' && $language=='sin')
							{
								// need to be corrected
								$playlist=array($promptroot.'subscriptionno',$promptroot.'digits/'.($count+1), $promptroot.'playsubscription-lands-part1',$promptroot.$parents[1]['prompt'],$promptroot.'playsubscription-lands-part2',sizeof($parents)>2?$promptroot.$parents[2]['prompt']:"",sizeof($parents)>2?$promptroot.'playsubscription-lands-part3':"", $promptroot.'playsubscription-lands-part4');
									
							}
							elseif ($subscriptionlist[$count]['servicetype']=='vehicles'  && $language=='eng')
							{
								$playlist=array($promptroot.'subscriptionno',$promptroot.'digits/'.($count+1), $promptroot.'playsubscription-vehicles-part1',$promptroot.'playsubscription-vehicles-part2',sizeof($parents)>2?$promptroot.$parents[2]['prompt']:"",sizeof($parents)>1?$promptroot.$parents[1]['prompt']:"",sizeof($parents)==1?$promptroot.$parents[0]['prompt']:"");
								
							}
							elseif ($subscriptionlist[$count]['servicetype']=='vehicles'  && $language=='sin')
							{
								$playlist=array($promptroot.'subscriptionno',$promptroot.'digits/'.($count+1), $promptroot.'playsubscription-vehicles-part1',$promptroot.'playsubscription-vehicles-part2',sizeof($parents)>2?$promptroot.$parents[2]['prompt']:"",sizeof($parents)>1?$promptroot.$parents[1]['prompt']:null,sizeof($parents)==1?$promptroot.$parents[0]['prompt']:"",$promptroot.'playsubscription-vehicles-part3');
											
							}
							
							$selection=-1;
							if($count==sizeof($subscriptionlist)-1)
							{
								
								array_push($playlist,$promptroot.'manageactivesubscriptions2' );
								$selection=$agi->play_concatenated_menu($playlist, '12');
							}
							else 
							{
								array_push($playlist,$promptroot.'manageactivesubscriptions1' );
								$selection=$agi->play_concatenated_menu($playlist, '123');
							}
					
							if($selection=='1')      // delete this subscription
							{
								deactivatesubscription($msisdn,$subscriptionlist[$count]['servicetype'],$parents,$subscriptionlist[$count]['subscriptionid']);
								unset($subscriptionlist[$count]);
								$subscriptionlist=array_values($subscriptionlist);
								
							}
							elseif($selection=='2'&& $count==0)          // go to previous menu
							{
								goto ManageRegistrations;
							}
							elseif($selection=='2')          // go back to the previous item
							{
								$count--;
							}
							elseif($selection=='3')          // go to the next item
							{
								$count++;
							}
						}
						return 98;
					}					
					
					elseif($promptlist[$selection]['name']=='inactivesubscriptions')
					{
						$subscriptionlist=$promptlist[$selection]['list'];
						$count=0;
						while ($count<sizeof($subscriptionlist))
						{
							$parents=getparents($subscriptionlist[$count]['serviceitem']);
							$agi->verbose($subscriptionlist[$count]['serviceitem'] ,true);
							if ($subscriptionlist[$count]['servicetype']=='lands' && $language=='eng')
							{
								$playlist=array($promptroot.'subscriptionno',$promptroot.'digits/'.($count+1), $promptroot.'playsubscription-lands-part1',$promptroot.'playsubscription-lands-part2',sizeof($parents) >2?$promptroot.'playsubscription-lands-part3':"",sizeof($parents) >2?$promptroot.$parents[2]['prompt']:"",sizeof($parents) >2?$promptroot.'playsubscription-lands-part4':"",$promptroot.'playsubscription-lands-part5',$promptroot.$parents[1]['prompt']);
								
							}
							elseif ($subscriptionlist[$count]['servicetype']=='lands' && $language=='sin')
							{
								// need to be corrected
								$playlist=array($promptroot.'subscriptionno',$promptroot.'digits/'.($count+1), $promptroot.'playsubscription-lands-part1',$promptroot.$parents[1]['prompt'],$promptroot.'playsubscription-lands-part2',sizeof($parents)>2?$promptroot.$parents[2]['prompt']:"",sizeof($parents)>2?$promptroot.'playsubscription-lands-part3':"", $promptroot.'playsubscription-lands-part4');

							}
							elseif ($subscriptionlist[$count]['servicetype']=='vehicles'  && $language=='eng')
							{
								$playlist=array($promptroot.'subscriptionno',$promptroot.'digits/'.($count+1), $promptroot.'playsubscription-vehicles-part1',$promptroot.'playsubscription-vehicles-part2',sizeof($parents)>2?$promptroot.$parents[2]['prompt']:"",sizeof($parents)>1?$promptroot.$parents[1]['prompt']:"",sizeof($parents)==1?$promptroot.$parents[0]['prompt']:"");
								
							}
							elseif ($subscriptionlist[$count]['servicetype']=='vehicles'  && $language=='sin')
							{
								$playlist=array($promptroot.'subscriptionno',$promptroot.'digits/'.($count+1), $promptroot.'playsubscription-vehicles-part1',$promptroot.'playsubscription-vehicles-part2',sizeof($parents)>2?$promptroot.$parents[2]['prompt']:"",sizeof($parents)>1?$promptroot.$parents[1]['prompt']:null,sizeof($parents)==1?$promptroot.$parents[0]['prompt']:"",$promptroot.'playsubscription-vehicles-part3');
											
							}
							// vehicle : you have subscribed to receive SMS alerts on toyota 110 cars. manufactured year, above 2012
							// Lands : you have subscribed to receive SMS alerts on lands arround homagama area in Colombo district. land size bellow 20 prchs
							$selection=-1;
							if($count==sizeof($subscriptionlist)-1)
							{
								array_push($playlist,$promptroot.'manageinactivesubscriptions2' );
								$selection=$agi->play_concatenated_menu($playlist, '123');
							}
							else
							{
								array_push($playlist,$promptroot.'manageinactivesubscriptions1' );
								$selection=$agi->play_concatenated_menu($playlist, '1234');
							}
					
							
					
							if($selection=='1')      // activate this subscription
							{
								activatesubscription($msisdn,$subscriptionlist[$count]['servicetype'],$parents,$subscriptionlist[$count]['subscriptionid']);
								unset($subscriptionlist[$count]);
								$subscriptionlist=array_values($subscriptionlist);
							}
							elseif($selection=='2')      // delete this subscription
							{
								deletesubscription($msisdn,$parents,$subscriptionlist[$count]['subscriptionid']);
								unset($subscriptionlist[$count]);		// do this based on the succes
								$subscriptionlist=array_values($subscriptionlist);
							}
							elseif($selection=='3'&& $count==0)          // go to previous menu
							{
								goto ManageRegistrations;
							}
							elseif($selection=='3')          // go back to the previous item
							{
								$count--;
							}
							elseif($selection=='4')          // go to the next item
							{
								$count++;
							}
						}
						return 98;
					}
					
				}
					
		}	

   }

   function set_language()
   {
		global $agi,$db,$msisdn,$language,$promptroot;
		$selection=-1;
        $selection=$agi->play_menu($promptroot.'selectlanguage','123',3);
        if ($selection=='1')     // sinhala
        {
                $db->sql("INSERT INTO `language` (`msisdn`,`language`) VALUES ('".$msisdn."','sin') ON DUPLICATE KEY UPDATE `language`='sin'","NONE");
                $language='sin';	// change this to 'sin'
                $agi->exec_setlanguage($language);   // set the language
        }
        elseif ($selection=='4')     // tamil
        {
                $db->sql("INSERT INTO `language` (`msisdn`,`language`) VALUES ('".$msisdn."','tam') ON DUPLICATE KEY UPDATE `language`='tam'","NONE");
                $language='eng';
                $agi->exec_setlanguage($language);   // set the language
        }
        else      // English
        {
                $db->sql("INSERT INTO `language` (`msisdn`,`language`) VALUES ('".$msisdn."','eng') ON DUPLICATE KEY UPDATE `language`='eng'","NONE");
                $language='eng';
                $agi->exec_setlanguage($language);   // set the language
        }  
   }

    $language='eng';
    $promptroot='classified/';
    $res="";
    $res = $db->sql("SELECT `language` from `language` where `msisdn`='".$msisdn."'", "ASSOC");    // get the language of teh Subscriber
	
    if (sizeof($res)==0)	// if no language record found
   	{
	   	$agi->exec_setlanguage($language);  // set the default language 
		$agi->stream_file($promptroot.($direction=='out' ? 'searchwelcome': 'welcome'), '');	// welcome
   		set_language();		// ask for te language
   	}
   	else	// has the language preference
   	{
		$language=$res[0]['language'];
	   	$agi->exec_setlanguage($language);   // set the language
   	}

 //  $language='en/classified';	// to be removed 
 // $agi->exec_setlanguage($language);	// to be removed

   Home:
   $service=$argv[3];
   $operation=$argv[4];
   $smstext=$argv[5];
   $registrationflow= $direction=='out'?'smssearch':'normalclassification';
   
   
   $agi->stream_file($promptroot.($direction=='out' ? 'searchwelcome': 'welcome'), '');	// welcome
   
   $agi->verbose("Starting Main Menu.....",1);
   $selection=-1;
   if($service=='vehicles')		// if the Service type was passed as an Argument in the AGI call (in SMS Search)
   {
   		$selection=1;
   }else if($service=='lands'){	// if the Service type was passed as an Argument in the AGI call (in SMS Search)
   		$selection=2;
   }
   else{	// if the Service type was passed as an Argument in the AGI call (in SMS Search) or an incoming call
   		$selection=$agi->play_menu($promptroot.'mainmenu','1234',3); // play main menu   	  
   }
   
   if ($selection=='4')     // change Language
   { 
	set_language();
	goto Home;

   }
   elseif ($selection=='5')     // Customercare Representative
   {
		// connect to the Customercare Representative
        goto Home;

   }
   elseif ($selection=='3')     // manage Registrations
   {
		$registrationtype=array('unprocessedadverts'=>true,'activeadverts'=>true,'inactiveadverts'=>true,'activesubscriptions'=>true,'inactivesubscriptions'=>true);
		$selection=-1;
		$selection=manage_registrations($registrationtype);
        if($selection==99)      // go back
        {
	        goto Home;
        }
        elseif($selection==98)          // go to main
        {
        	goto Home;
        }
        elseif($selection==97)          // go to main
        {
            $agi->stream_file($promptroot.'noregistrations','');
        	goto Home;
        }


   }
   elseif ($selection=='1' || $selection=='2')     //2()- Lands          1)-Vehicles
   {
   	$level1=$selection;
   	$servicetype=($level1==2? 'lands':'vehicles');
   	LandVehiMain:   
   	$selection=-1;
   	if($operation=='sell'){			// if the Operation (Buy/Sell) has been passed as an argument (in SMS Search), it will skip the categorie's main Menu
   		$selection=1;
   	}
   	else if($operation=='buy'){		// if the Operation (Buy/Sell) has been passed as an argument (in SMS Search), it will skip the categorie's main Menu
   		$selection=2;
   	}
   	else{
   		$selection=-1;
   		$selection=$agi->play_menu($promptroot.$servicetype.'main','123',3); // play Level2 main menu
   	}
   	 	
   	
   	if($selection=='3') // 		 back to main menu
   	{
   		goto Home;
   	}
   	elseif($selection=='1')	// sell lands/vehicles
   	{
   		LandVehiSell:
   		$selection=-1;
   		$selection=$agi->play_menu($promptroot.'sellermenu','1234',3);	// record advert menu
   		if($selection=='4')
   		{
   			goto LandVehiMain;	// go back
   		}
   		elseif($selection=='2')	//  Listen and Manage Adverts
   		{
   			$registrationtype=array('unprocessedadverts'=>true,'activeadverts'=>true,'inactiveadverts'=>true);
   			$selection=-1;
   			$selection=manage_registrations($registrationtype,"'".$servicetype."'");
   			$agi->verbose("selection : ".$selection);
   			if($selection==99)      // go back
   			{
   				goto LandVehiSell;
   			}
   			elseif($selection==98)          // go to main
   			{
   				goto Home;
   			}
   			elseif($selection==97)          // go to main
   			{
   				$agi->stream_file($promptroot.'noadvertistments','');
   				goto Home;
   			}
   
   		}
   		elseif ($selection=='3' && $servicetype=='vehicles')	// listen to sample Vehicle advedrt
   		{
   			$agi->stream_file($promptroot.'vehicleadvertsample', '');
   			goto LandVehiSell;
   		}
   		elseif ($selection=='3' && $servicetype=='lands')		// listen to sampole Lands advert
   		{
   			$agi->stream_file($promptroot.'landadvertsample', '');
   			goto LandVehiSell;
   		}
   		elseif($selection=='1')		// Record the advertisment
   		{
   			RecordStart:
   			$agi->stream_file($promptroot.'recordstart', '');
   			$filename=date("YmdHis")."-".$msisdn;
   			$agi->record_file("classifiedadverts/".$filename, 'gsm','#', 20000, NULL, true, NULL);
   				
   			PostRecord:
   			$selection=-1;
   			$selection=$agi->play_menu($promptroot.'postrecordmenu','123',3);
   
   			if($selection=='3')
   			{
   				$output = shell_exec("rm -f /var/lib/asterisk/sounds/classifiedadverts/".$filename.".gsm");
   				goto RecordStart;
   			}
   			elseif($selection=='1')
   			{
   				publish_advert($msisdn, $language, $servicetype, $filename);
   				
   				goto Home;
   			}
   			elseif($selection=='2')
   			{
   				$agi->stream_file('/var/lib/asterisk/sounds/classifiedadverts/'.$filename, '');
   				goto PostRecord;
   			}
   			else
   				$agi->hangup();
   		}
   
   
   	}
   	elseif($selection=='2')			// buy lands/vehicles
   	{
   		BuyerMain:
   		$selection=-1;
   		if ($registrationflow=='smssearch'){
   			goto StartSubscription;
   		}
   		else{
   			
   			$selection=$agi->play_menu($promptroot.$servicetype.'buyermenu','123',3);	// Buyers Main Menu   			   
   		}
   		
   		
   		if($selection=='3')		// go back
   		{
   			goto LandVehiMain;
   		}
   		elseif($selection=='2')	// listen and manage previous subscriptions
   		{   
   			$registrationtype=array('activesubscriptions'=>true,'inactivesubscriptions'=>true);
   			$selection=-1;
   			$selection=manage_registrations($registrationtype,"'".$servicetype."'");
   			if($selection==99)      // go back
   			{
   				goto BuyerMain;
   			}
   			elseif($selection==98)          // go to main
   			{
   				goto Home;
   			}
   			elseif($selection==97)          // go to main
   			{
   				$agi->stream_file($promptroot.'nosubscriptions','');
   				goto BuyerMain;
   			}   
   		}
   		elseif($selection=='1')	// new subscription
   		{
   			StartSubscription:
   			$level=1;
   			$res=null;
   			
   			$levelhistory[$level]=array('registrationflow'=>$registrationflow, 'parent'=>($servicetype=='lands' ? $landsparentid:$vehiclesparentid));
   				
   			
   			while(true){   				
   				$parent=$levelhistory[$level]['parent'];
   				$regflow=$levelhistory[$level]['registrationflow'];
   				if($regflow=='smssearch')
   				{
   					if ($smstext!=""){			// if there is a Sentence to search
   						$res = $db->sql("SELECT `itemid`,`name`,concat('classification/',`prompt`) as `prompt`,MATCH (`smstext`,`keywords`) AGAINST ('".$smstext."' ) as score from `classification` where MATCH (`smstext`,`keywords`) AGAINST ('".$smstext."' ) and `servicetype`='".$servicetype."'  order by level desc,score desc limit 7", "ASSOC");
   						if (sizeof($res)==0){
   							$levelhistory[$level]=array('registrationflow'=>'normalclassification', 'parent'=>($servicetype=='lands' ? $landsparentid:$vehiclesparentid));
   							continue;
   						}
   						
   					}
   					else
   					{
   						$levelhistory[$level]=array('registrationflow'=>'normalclassification', 'parent'=>($servicetype=='lands' ? $landsparentid:$vehiclesparentid));
   						continue;
   					}	
   					
   				}
   				else if($regflow=='secondregistration'){
   						
   					$res = $db->sqlmultiquery("CALL `getmatchingitems` ('".$msisdn."',".$parent.")", "ASSOC");
   					$agi->verbose(var_export($res,true));
   					if (sizeof($res)==0){
   						$levelhistory[$level]=array('registrationflow'=>'normalclassification', 'parent'=>($servicetype=='lands' ? $landsparentid:$vehiclesparentid));
   						continue;				
   					}
   				}   				 				
   				else{		// normalclassification
   					$res = $db->sql("SELECT `itemid`,`name`,concat('classification/',`prompt`) as `prompt` from `classification` where `parentid`=".$parent." order by `rank` desc limit 7", "ASSOC");    // select the level 1 items
   					if (sizeof($res)==0)		// check if no children found
   					{
   						if ($parent==1||$parent==2){
   							$agi->stream_file($promptroot.'temperror', '');	// no Root Classification
   							$agi->hangup();
   						}
   						
   						$selection=-1;
   						$itemparents=getparents($parent);
   						$playlist=null;
   						if($servicetype=='lands' && $language=='sin'){
   							$playlist=array($promptroot.$itemparents[1]['prompt'],$promptroot.'playsubscription-lands-part2',sizeof($itemparents)>2?$promptroot.$itemparents[2]['prompt']:"",sizeof($itemparents)>2?$promptroot.'playsubscription-lands-part3':"", $promptroot.'lconfirmsubscription');
   						}
   						else if($servicetype=='vehicles' && $language=='sin'){
   							$playlist=array($promptroot.'playsubscription-vehicles-part2',sizeof($itemparents)>2?$promptroot.$itemparents[2]['prompt']:"",sizeof($itemparents)>1?$promptroot.$itemparents[1]['prompt']:null,sizeof($itemparents)==1?$promptroot.$itemparents[0]['prompt']:"",$promptroot.'vconfirmsubscription');
   						}
   						else if($servicetype=='lands' && $language=='eng'){
   							$playlist=array($promptroot.'playsubscription-lands-part2',sizeof($itemparents)>2?$promptroot.'playsubscription-lands-part3':"",sizeof($itemparents)>2?$promptroot.$itemparents[2]['prompt']:"",sizeof($itemparents)>2?$promptroot.'playsubscription-lands-part4':"",$promptroot.'playsubscription-lands-part5',$promptroot.$itemparents[1]['prompt'], $promptroot.'lconfirmsubscription');
   						}
   						else if($servicetype=='vehicles' && $language=='eng'){
   							$playlist=array($promptroot.'playsubscription-vehicles-part2',sizeof($itemparents)>2?$promptroot.$itemparents[2]['prompt']:"",sizeof($itemparents)>1?$promptroot.$itemparents[1]['prompt']:"",sizeof($itemparents)==1?$promptroot.$itemparents[0]['prompt']:"", $promptroot.'vconfirmsubscription');
   						}
   						else{
   							$agi->stream_file($promptroot.'thankyou', '');
   							$agi->hangup();
   						}
   						
   						$selection=$agi->play_concatenated_menu($playlist, '123');
   						if($selection=='2')      // go back
   						{
	   						if($level==1)
	   							goto BuyerMain;
		   					else
		   					{
		   						$level--;
		   						
		   					}
   							continue;
   							
   						}
   						elseif($selection=='1')              // Registration Confirmed
   						{
   							$result=subscribe_customer($msisdn,$servicetype,$parent,$itemparents);
   							if ($result=='1')		// second Registration
   							{  								
   								$levelhistory[$level]=array('registrationflow'=>'secondregistration', 'parent'=>$parent);
   								continue;								
   							}
   							elseif ($result=='3')
   							{
   								$agi->stream_file($promptroot.'thankyou', '');
   								$agi->hangup();
   								
   							}
   							else
   							{   								
   								goto Home;
   							}
   						}
   						else          // go to main
   						{
   							goto Home;
   						}
   					}
   					
   				}
   				
   				// After getting the List of Classification
   				
   				array_push($res,array('itemid'=>9999999, 'name'=>'nonoftheabove','prompt'=>'nonoftheabove'));
   				$agi->stream_file($promptroot.($servicetype=='lands' ? 'lbuyerflowprompt':'vbuyerflowprompt').(($level%2) +1), '');	// select the area or th evehicle category
   				 	
   				$selection=-1;
   				$selection=$agi->play_dynamic_menu($promptroot,$res);	// play the level's dynamic menu
   				
   				if($selection==99)	// go back
   				{
   					if($level==1)
   						goto BuyerMain;
   					else
   					{
   						$level--;
   						continue;
   					}
   					
   				}
   				elseif($selection==98)		// go to main
   				{
   					goto Home;
   				}
   				else		// item selected
   				{
   					if($res[$selection]['itemid']==9999999)	// non of the above
   					{
   						$agi->stream_file($promptroot.'nonoftheabove-'.$servicetype, '');	// not found the are or the vehicle
   						continue;
   					}
   						
   					
   					$level++;
   					$levelhistory[$level]=array('registrationflow'=>'normalclassification', 'parent'=>$res[$selection]['itemid']);
   			
   				}
   				
   			}
   			
   		}
   	}
   
   }
   $agi->hangup();
   
    
?>


